namespace CSharpPro._1023mulu;

public class Worksix
{

class BubbleSort
{
    // 整型数组冒泡排序
    public static void Sort(int[] arr)
    {
        int n = arr.Length;
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = 0; j < n - i - 1; j++)
            {
                if (arr[j] > arr[j + 1])
                {
                    // 交换元素
                    (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
                }
            }
        }
    }

    // 泛型冒泡排序（支持任何可比较的类型）
    public static void Sort<T>(T[] arr) where T : IComparable<T>
    {
        int n = arr.Length;
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = 0; j < n - i - 1; j++)
            {
                if (arr[j].CompareTo(arr[j + 1]) > 0)
                {
                    (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
                }
            }
        }
    }

    // 打印数组
    public static void PrintArray(int[] arr)
    {
        foreach (var num in arr)
        {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }

    // 测试方法
    public static void Test()
    {
        Console.WriteLine("=== 冒泡排序测试 ===");
        
        // 测试1：整型数组排序
        int[] numbers = { 64, 34, 25, 12, 22, 11, 90 };
        Console.WriteLine("排序前:");
        PrintArray(numbers);
        
        Sort(numbers);
        Console.WriteLine("排序后:");
        PrintArray(numbers);

        // 测试2：字符串数组排序
        string[] names = { "张三", "李四", "王五", "赵六", "Alice", "Bob" };
        Console.WriteLine("\n字符串排序前:");
        foreach (var name in names) Console.Write(name + " ");
        
        Sort(names);
        Console.WriteLine("\n字符串排序后:");
        foreach (var name in names) Console.Write(name + " ");
        Console.WriteLine();

        // 测试3：用户输入排序
        Console.WriteLine("\n=== 用户输入排序 ===");
        Console.Write("请输入要排序的数字个数: ");
        int count = int.Parse(Console.ReadLine());
        
        int[] userNumbers = new int[count];
        for (int i = 0; i < count; i++)
        {
            Console.Write($"请输入第 {i + 1} 个数字: ");
            userNumbers[i] = int.Parse(Console.ReadLine());
        }
        
        Console.WriteLine("排序前:");
        PrintArray(userNumbers);
        
        Sort(userNumbers);
        Console.WriteLine("排序后:");
        PrintArray(userNumbers);
    }
}

// 学生类
public class Student : IComparable<Student>
{
    // 字段
    private string _studentId;
    private string _name;
    private int _age;
    private string _gender;
    private double _score;
    private string _className;

    // 属性
    public string StudentId
    {
        get => _studentId;
        set
        {
            if (string.IsNullOrWhiteSpace(value))
                throw new ArgumentException("学号不能为空");
            _studentId = value;
        }
    }

    public string Name
    {
        get => _name;
        set
        {
            if (string.IsNullOrWhiteSpace(value))
                throw new ArgumentException("姓名不能为空");
            if (value.Length > 20)
                throw new ArgumentException("姓名长度不能超过20个字符");
            _name = value;
        }
    }

    public int Age
    {
        get => _age;
        set
        {
            if (value < 6 || value > 60)
                throw new ArgumentException("年龄必须在6-60岁之间");
            _age = value;
        }
    }

    public string Gender
    {
        get => _gender;
        set
        {
            if (value != "男" && value != "女")
                throw new ArgumentException("性别必须是'男'或'女'");
            _gender = value;
        }
    }

    public double Score
    {
        get => _score;
        set
        {
            if (value < 0 || value > 100)
                throw new ArgumentException("成绩必须在0-100之间");
            _score = value;
        }
    }

    public string ClassName
    {
        get => _className;
        set
        {
            if (string.IsNullOrWhiteSpace(value))
                throw new ArgumentException("班级不能为空");
            _className = value;
        }
    }

    // 等级属性（只读）
    public string GradeLevel
    {
        get
        {
            return _score switch
            {
                >= 90 => "优秀",
                >= 80 => "良好",
                >= 70 => "中等",
                >= 60 => "及格",
                _ => "不及格"
            };
        }
    }

    // 构造函数
    public Student(string studentId, string name, int age, string gender, double score, string className)
    {
        StudentId = studentId;
        Name = name;
        Age = age;
        Gender = gender;
        Score = score;
        ClassName = className;
    }

    // 默认构造函数
    public Student() { }

    // 方法：显示学生信息
    public void DisplayInfo()
    {
        Console.WriteLine($"学号: {StudentId}");
        Console.WriteLine($"姓名: {Name}");
        Console.WriteLine($"年龄: {Age}");
        Console.WriteLine($"性别: {Gender}");
        Console.WriteLine($"成绩: {Score}");
        Console.WriteLine($"班级: {ClassName}");
        Console.WriteLine($"等级: {GradeLevel}");
        Console.WriteLine(new string('-', 30));
    }

    // 方法：判断是否及格
    public bool IsPassed()
    {
        return Score >= 60;
    }

    // 实现IComparable接口，按成绩排序
    public int CompareTo(Student other)
    {
        return other.Score.CompareTo(Score); // 降序排列
    }

    // 重写ToString方法
    public override string ToString()
    {
        return $"学号:{StudentId} 姓名:{Name} 年龄:{Age} 性别:{Gender} 成绩:{Score} 班级:{ClassName} 等级:{GradeLevel}";
    }

    // 重写Equals方法
    public override bool Equals(object obj)
    {
        return obj is Student student && StudentId == student.StudentId;
    }

    // 重写GetHashCode方法
    public override int GetHashCode()
    {
        return StudentId.GetHashCode();
    }
}

// 学生管理类
public class StudentManager
{
    private List<Student> students = new List<Student>();

    // 添加学生
    public void AddStudent(Student student)
    {
        if (students.Any(s => s.StudentId == student.StudentId))
        {
            throw new ArgumentException("学号已存在！");
        }
        students.Add(student);
        Console.WriteLine("添加学生成功！");
    }

    // 删除学生
    public void RemoveStudent(string studentId)
    {
        var student = students.FirstOrDefault(s => s.StudentId == studentId);
        if (student != null)
        {
            students.Remove(student);
            Console.WriteLine("删除学生成功！");
        }
        else
        {
            Console.WriteLine("未找到该学号的学生！");
        }
    }

    // 查找学生
    public Student FindStudent(string studentId)
    {
        return students.FirstOrDefault(s => s.StudentId == studentId);
    }

    // 显示所有学生
    public void DisplayAllStudents()
    {
        if (students.Count == 0)
        {
            Console.WriteLine("没有学生信息！");
            return;
        }

        Console.WriteLine($"\n共有 {students.Count} 名学生:");
        foreach (var student in students)
        {
            student.DisplayInfo();
        }
    }

    // 按成绩排序
    public void SortByScore()
    {
        students.Sort();
        Console.WriteLine("按成绩降序排列完成！");
    }

    // 统计信息
    public void DisplayStatistics()
    {
        if (students.Count == 0)
        {
            Console.WriteLine("没有学生信息！");
            return;
        }

        double average = students.Average(s => s.Score);
        double maxScore = students.Max(s => s.Score);
        double minScore = students.Min(s => s.Score);
        int passCount = students.Count(s => s.IsPassed());
        int failCount = students.Count - passCount;

        Console.WriteLine("\n=== 统计信息 ===");
        Console.WriteLine($"总人数: {students.Count}");
        Console.WriteLine($"平均分: {average:F2}");
        Console.WriteLine($"最高分: {maxScore}");
        Console.WriteLine($"最低分: {minScore}");
        Console.WriteLine($"及格人数: {passCount}");
        Console.WriteLine($"不及格人数: {failCount}");
    }

    // 按班级分组显示
    public void DisplayByClass()
    {
        var grouped = students.GroupBy(s => s.ClassName)
                             .OrderBy(g => g.Key);

        foreach (var group in grouped)
        {
            Console.WriteLine($"\n班级: {group.Key}");
            foreach (var student in group)
            {
                Console.WriteLine($"  {student.Name} - {student.Score}");
            }
        }
    }
}

// 测试程序
class Program
{
    static void Main(string[] args)
    {
        // 测试冒泡排序
        BubbleSort.Test();

        Console.WriteLine("\n" + new string('=', 50) + "\n");

        // 测试学生管理系统
        TestStudentSystem();
    }

    static void TestStudentSystem()
    {
        StudentManager manager = new StudentManager();

        // 添加测试数据
        try
        {
            manager.AddStudent(new Student("1001", "张三", 20, "男", 85.5, "计算机1班"));
            manager.AddStudent(new Student("1002", "李四", 19, "女", 92.0, "计算机1班"));
            manager.AddStudent(new Student("1003", "王五", 21, "男", 58.0, "计算机2班"));
            manager.AddStudent(new Student("1004", "赵六", 20, "女", 76.5, "计算机2班"));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"错误: {ex.Message}");
        }

        // 显示所有学生
        manager.DisplayAllStudents();

        // 显示统计信息
        manager.DisplayStatistics();

        // 排序并显示
        manager.SortByScore();
        Console.WriteLine("\n按成绩排序后:");
        manager.DisplayAllStudents();

        // 按班级分组显示
        Console.WriteLine("\n按班级分组:");
        manager.DisplayByClass();

        // 测试查找功能
        Console.WriteLine("\n=== 查找学生 ===");
        var student = manager.FindStudent("1001");
        if (student != null)
        {
            Console.WriteLine("找到学生:");
            student.DisplayInfo();
        }

        // 测试删除功能
        Console.WriteLine("\n=== 删除学生 ===");
        manager.RemoveStudent("1003");
        manager.DisplayAllStudents();
    }
}
}